//
//  CRCTool.swift
//  AreaMeasureDevice
//
//  Created by iOS on 2021/6/21.
//

import UIKit

class CRCTool: NSObject {

    static let instance = CRCTool()

    private var crcTable: [Int] = []

    /// 多项式 CRC-16/XMODEM
    private let gPloy = 0x1021

    /// 传入[UInt8]返回CRC16检验数据
    func getCRCResult(data:[UInt8]) ->[UInt8] {
        var crc = getCrc(data: data)
        var crcArr: [UInt8] = [0, 0]
        for i in (0..<2).reversed() {
            crcArr[i] = UInt8(crc % 256)
            crc >>= 8
        }
        return crcArr
    }

    ///生成0-255的CRC16代码
    private func computeCrcTable(){
        for i in 0..<256 {
            crcTable.append(getCrcOfByte(aByte: i))
        }
    }

    private func getCrcOfByte(aByte:Int) -> Int {
        var value = aByte << 8
        for _ in 0 ..< 8 {
            if value & 0x8000 != 0 {
                value = (value << 1) ^ gPloy
            }else{
                value = value << 1
            }
        }
        value = value & 0xFFFF
        return value
    }

    private func getCrc(data:[UInt8]) -> UInt16 {
        var crc = 0
        let dataInt:[Int] = data.map{Int($0)}
        let length = data.count
        for i in 0 ..< length {
            crc = ((crc & 0xFF) << 8) ^ crcTable[(((crc & 0xFF) >> 8) ^ dataInt[i]) & 0xFF]
        }
        crc = crc & 0xFFFF
        return UInt16(crc)
    }

}
